var crypto = require('crypto');
var fs = require('fs');

exports.md5 = function md5 (str) {
  return crypto.createHash('md5').update(new Buffer(str,'utf-8')).digest('hex');
};

exports.fileMD5Async = function (filePath) {
    return new Promise(function(resolve,reject){
        var md5 = crypto.createHash('md5');
        var s = fs.createReadStream(filePath);
        s.on('data',function(chunk) {
            md5.update(chunk);
        });
        s.on('end',function() {
            var str = md5.digest('hex');
            resolve(str);
        });
    });
}

exports.toBase64 = function (szInput) {
    return new Buffer(szInput).toString("base64");
}
exports.fromBase64 = function szInput() {
    new Buffer(szInput,"base64").toString();
}

exports.rsaDigest = function(str) {
    var hash = crypto.createHash("SHA1").update(str);
    return hash.digest('hex');
}

//RSA 签名
exports.rsaSign = function (privateKey,str) {
    //var privateKey = fs.readFileSync('trjPrivate.pem').toString();
    var signer = crypto.createSign("RSA-SHA1").update(new Buffer(str,'utf-8'));
    return signer.sign(privateKey,'base64');
}

//RSA 签名验证
exports.rsaSignVerify = function (publicKey,str,sign) {
    //var publicKey = fs.readFileSync('alipayPublis.pem').toString();
    var verifier = crypto.createVerify('RSA-SHA1').update(new Buffer(str,'utf-8'));
    return verifier.verify(publicKey,sign,'base64');
}

//RSA2 签名
exports.rsa2Sign = function (privateKey,str) {
  /*var signer = crypto.createSign("RSA-SHA256").update(new Buffer(str,'utf-8'));
  return signer.sign(privateKey,'base64');*/
  var signer = crypto.createSign("RSA-SHA256").update(new Buffer(str,'utf-8'));
  return signer.sign(privateKey,'base64');
}

//RSA256 签名验证
exports.rsa2SignVerify = function (publicKey,str,sign) {
  var verifier = crypto.createVerify('RSA-SHA256').update(new Buffer(str,'utf-8'));
  return verifier.verify(publicKey,sign,'base64');
}

exports.keyGenerator = function generator (len){
	len = len || 12;
	var chars = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var key = '';
	var maxPos = chars.length;
	for (var i = 0; i < len; ++i){
		key += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return key;
};

exports.verifyCodeGenerator = function(len){
    len = len || 6;
    var chars = "0123456789";
    var key = '';
    var maxPos = chars.length;
    for (var i = 0; i < len; ++i){
        key += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return key;
};
